<?php
namespace app\common\model;
use think\Model;
class Base extends Model{
    
    protected function paginate() {
        $request = request();
        $this->lastPkId = $request->get('lastPk', 0, 'intval');
        $this->pageSize = $request->get('pageSize', 20, 'intval');
        $this->pageOffset = ($request->get('p', 1, 'intval') - 1) * $this->pageSize;
        unset($request);
        
        return $this;
    }
    
    /**
     * 根据主键判断某人是否存在
     * **/
    public function isExistsByPk($pkId) {
        $pk = $this->getPk();
        $rs = $this->field($pk)->where(["$pk" => $pkId])->find();
        return $rs ? true : false;
    }
    
    /**
     * 新增一条数据，返回新增的主键
     * **/
    public function add($data){
        $rs = $this->data($data)->isUpdate(false)->save();
        if(!$rs) return false;
        $pk = $this->getPk();
        return $this->$pk;
    }
    
    /**
     * 新增多条数据
     * **/
    public function addAll($dataSet){
        $rowNumber = 0;
        $pk = $this->getPk();
        $rows = $this->isUpdate(false)->saveAll($dataSet, false)->toArray();
        foreach ($rows as $row) {
            if(isset($row[$pk])){
                $rowNumber ++;
            }
        }
        
        return $rowNumber;
    }
    
    
    /**
     * 更新数据
     * **/
    public function modify($where ,$data){
        $result = $this->where($where)->update($data);
        return $result;
    }
    
    /**
     * 查询单条数据
     * **/
    public function findOne($where = [], $field = '*') {
        $result = $this->where($where)->field($field)->find();
        return $result ? $result->toArray() : [];
    }
    
    /**
     * 查询多条条数据
     * **/
    public function findAll($where = [], $field = '*') {
        $result = $this->where($where)->field($field)->select();
        return $result->toArray();
    }
    
    public function values($where = [], $field) {
        $values = [];
        $result = $this->where($where)->field($field)->select()->toArray();
        if(!empty($result)) {
            foreach ($result as $val) {
                array_push($values, $val[$field]);
            }
        }
        
        return $values;
    }

    
}